package com.whq.thrift.api.web.admin.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.WebApplicationContext;

import com.whq.common.StringUtil;
import com.whq.thrift.api.common.spring.ReloadableConfManager;
import com.whq.thrift.api.web.admin.db.admin.PermissionUri;
import com.whq.thrift.api.web.admin.db.admin.UserMermission;
import com.whq.thrift.api.web.admin.service.admin.UserInfoService;
import com.whq.thrift.api.web.admin.util.LoginUtil;

/**
 * 登录Filter
 * 
 * @author wanghuaiqiang
 * 
 */
public class ChkLoginFilter implements Filter {
//	private Logger logger = LoggerFactory.getLogger(GetSsoInfoFilter.class);
	private WebApplicationContext ctx;

	public void init(FilterConfig filterConfig) throws ServletException {
		ServletContext servletContext = filterConfig.getServletContext();
		Object ob = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		ctx = (WebApplicationContext) ob;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
//		HttpServletResponse resp = (HttpServletResponse) response;
		
		String loginTicket = LoginUtil.getLoginTicket(req);
		request.setAttribute("loginTicket", loginTicket);
		
		if (StringUtil.isBlank(loginTicket)) {
			req.getRequestDispatcher("/WEB-INF/jsp/common/needLogin.jsp").forward(request, response);
			return ;
		}
		
		boolean superAdmin = false;
		Set<String> userPermissionUriSet = new HashSet<String>(0);
		Set<String> userPermissionUriWithoutContextSet = new HashSet<String>(0);
		
		ReloadableConfManager reloadableConfManager = (ReloadableConfManager) ctx.getBean("reloadableConfManager");
		String superAdminsStr = reloadableConfManager.getPropertyValue("super.admins", null, "");
		Set<String> superAdminSet = StringUtil.split2set(superAdminsStr, "\\,");
		if (superAdminSet.contains(loginTicket)) {
			superAdmin = true;
		} else {
			UserInfoService userInfoService = (UserInfoService) ctx.getBean(UserInfoService.class);
			
			Set<Integer> userPermissionIdSet = new HashSet<Integer>(0);
			List<UserMermission> userPerssionsList = userInfoService.findUserMermissionByEmail(loginTicket);
			if (userPerssionsList != null) {
				for (Iterator<UserMermission> iterator = userPerssionsList.iterator(); iterator.hasNext();) {
					UserMermission userMermission = (UserMermission) iterator.next();
					if (userMermission != null) {
						userPermissionIdSet.add(userMermission.getPermissionId());
					}
				}
			}
			
			String contextRootPath = req.getContextPath();
			if ("/".equals(contextRootPath)) {
				contextRootPath = "";
			}
			
			List<PermissionUri> allPermissionsList = userInfoService.findPermissionByMap();
			if (allPermissionsList != null) {
				for (Iterator<PermissionUri> iterator = allPermissionsList.iterator(); iterator.hasNext();) {
					PermissionUri permissionUri = (PermissionUri) iterator.next();
					if ( (permissionUri != null) && (userPermissionIdSet.contains(permissionUri.getPermissionId())) ) {
						userPermissionUriSet.add(contextRootPath + permissionUri.getUri());
						userPermissionUriWithoutContextSet.add(permissionUri.getUri());
					}
				}
			}
		}
		
		String requestUri = req.getRequestURI();
		if ( (!superAdmin)
				&& (!userPermissionUriSet.contains(requestUri)) 
				) {
			req.getRequestDispatcher("/WEB-INF/jsp/common/permissionDenied.jsp").forward(request, response);
			return ;
		}
		
		request.setAttribute("superAdmin", superAdmin);
		request.setAttribute("userPermissionUriWithoutContextSet", userPermissionUriWithoutContextSet);
		
		chain.doFilter(request, response);
	}

	public void destroy() {

	}

}
